import { DefaultLoadingUI } from './default-loading-ui';


abstract class AbstractLoadingScreen {

    public static displayLoadingUI: () => void;

    public static hideLoadingUI: () => void;

    public static loadingUIBackgroundColor: string;

    public static loadingUIText: string;
}

/**
 * 默认加载页面
 * @param canvas 画布元素
 * @param loadingUIText 加载时的文字
 * @param customUI 自定义的ui元素
 */
class DefaultLoadingScreen extends AbstractLoadingScreen {
    private static _added: boolean = false;
    private static _ui: HTMLElement;
    private static _resize: { (): void };
    private static _canvas: HTMLCanvasElement;
    private static _resizeObserver: ResizeObserver | null = null;

    public static loadingUIBackgroundColor: string = '#000000';
    public static loadingUIText: string;

    public static initialize(canvas: HTMLCanvasElement, loadingUIText: string, customUI: HTMLElement | null) {
        this._canvas = canvas;
        this.loadingUIText = loadingUIText;
        if (customUI) {
            const clone = customUI.cloneNode(true);
            this._ui = clone as HTMLElement;
        } else {
            this._ui = DefaultLoadingUI;
        }
        this._resize = () => {
            const canvasRect = this._canvas.getBoundingClientRect();
            const canvasPositioning = window.getComputedStyle(this._canvas).position;
            if (!this._ui) {
                return;
            }
            this._ui.style.position = canvasPositioning === "fixed" ? "fixed" : "absolute";
            this._ui.style.left = canvasRect.left + "px";
            this._ui.style.top = canvasRect.top + "px";
            this._ui.style.width = canvasRect.width + "px";
            this._ui.style.height = canvasRect.height + "px";
            this._ui.style.transition = "opacity 1s ease-in 0.5s";
            this._ui.style.zIndex = '1000';
        };
    }

    public static displayLoadingUI(): void {
        this._ui.style.opacity = "1";
        if (this._added) return;
        this._added = true;
        this._resize();
        if (!this._resizeObserver) {
            this._resizeObserver = new ResizeObserver((entries) => {
                for (let i = 0; i < entries.length; i++) {
                    this._resize();
                }
            });
        }
        this._resizeObserver.observe(this._canvas);
        document.body.appendChild(this._ui);
    }

    public static hideLoadingUI(): void {
        if (!this._added) return;

        this._added = false;
        const onTransitionEnd = () => {
            this._ui.remove();
            if (this._resizeObserver) {
                this._resizeObserver.disconnect();
                this._resizeObserver = null;
            }
        };
        this._ui.style.opacity = "0";
        this._ui.addEventListener("transitionend", onTransitionEnd);

    }
}

export { DefaultLoadingScreen, AbstractLoadingScreen };